package net.xdclass.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.common.JsonData;
import net.xdclass.common.PageJsonData;
import net.xdclass.common.constant.Cons;
import net.xdclass.common.enums.BizCodeEnum;
import net.xdclass.common.enums.ProductOrderStateEnum;
import net.xdclass.common.enums.StockTaskStateEnum;
import net.xdclass.common.exception.BizException;
import net.xdclass.common.message.MessageInfo;
import net.xdclass.product.feign.OrderFeignClient;
import net.xdclass.product.mapper.ProductTaskMapper;
import net.xdclass.product.message.ProductMessage;
import net.xdclass.product.message.ProductMessageProducer;
import net.xdclass.product.model.ProductDO;
import net.xdclass.product.mapper.ProductMapper;
import net.xdclass.product.model.ProductTaskDO;
import net.xdclass.product.model.vo.ProductVO;
import net.xdclass.product.request.LockProductRequest;
import net.xdclass.product.request.OrderItemRequest;
import net.xdclass.product.service.ProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaya
 * @since 2023-12-13
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductTaskMapper productTaskMapper;
    @Autowired
    private ProductMessageProducer productMessageProducer;
    @Autowired
    private OrderFeignClient orderFeignClient;

    /**
     * 查询商品详情
     *
     * @param productId
     * @return
     */
    @Override
    public ProductVO selectProductById(Long productId) {
        ProductDO productDO = productMapper.selectById(productId);
        return toVO(productDO);
    }

    /**
     * ids 批量查询商品
     *
     * @param productIds
     * @return
     */
    @Override
    public List<ProductVO> selectProductByIds(List<Long> productIds) {
        QueryWrapper<ProductDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(ProductDO::getId, productIds);
        List<ProductDO> dos = productMapper.selectList(wrapper);
        return dos.stream().map(this::toVO).collect(Collectors.toList());
    }

    /**
     * 释放商品库存
     * 1、查询task
     * 2、查询订单状态
     *
     * @param messageInfo
     * @return
     */
    @Transactional
    @Override
    public boolean releaseProductStock(MessageInfo messageInfo) {
        if (!(messageInfo instanceof ProductMessage)){
            return true;
        }
        ProductMessage message = (ProductMessage) messageInfo;
        Long taskId = message.getTaskId();
        ProductTaskDO task = productTaskMapper.selectOne(Wrappers.<ProductTaskDO>lambdaQuery()
                .eq(ProductTaskDO::getId, taskId));
        if (task == null){
            log.warn("商品库存释放任务不存在。【{}】", message);
            return true;
        }
        if (StockTaskStateEnum.LOCK.equals(task.getLockState())){
            // 查询订单 PAY -> FINISH;
            JsonData data = orderFeignClient.queryOrderState(message.getOutTradeNo());
            if (data != null && Cons.SUCCESS.equals(data.getCode())){
                String state = data.getData().toString(); // NPE
                if (ProductOrderStateEnum.NEW.name().equalsIgnoreCase(state)){
                    log.info("订单尚未支付。【{}】", task.getOutTradeNo());
                    return false;
                }
                if (ProductOrderStateEnum.PAY.name().equalsIgnoreCase(state)){
                    // 更新任务状态
                    task.setLockState(StockTaskStateEnum.FINISH);
                    productTaskMapper.updateById(task);
                    return true;
                }
            }
            // TODO 远程调用失败？？直接释放库存？？？
            log.info("订单不存在或已取消，释放商品库存。【{}】", task.getOutTradeNo());
            task.setLockState(StockTaskStateEnum.CANCEL);
            productTaskMapper.updateById(task);
            int rows = productMapper.releaseProductStock(task.getProductId(), task.getBuyNum());
            if (rows == 1){
                return true;
            }
        }else {
            log.info("商品库存释放任务非LOCK。【{}】", task);
            return true;
        }
        return false;
    }

    /**
     * 锁定商品库存
     * 1、查询商品信息
     * 2、新增商品锁定记录
     * 3、发送解除锁定mq延迟消息
     * @param request
     * @return
     */
    @Override
    public JsonData lockProduct(LockProductRequest request) {
        String orderOutTradeNo = request.getOrderOutTradeNo();
        List<OrderItemRequest> orderItemList = request.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList) || StringUtils.isEmpty(orderOutTradeNo)){
            return JsonData.buildSuccess();
        }

        List<Long> productIds = orderItemList.stream().map(OrderItemRequest::getProductId).collect(Collectors.toList());
        List<ProductVO> products = selectProductByIds(productIds);
        Map<Long, ProductVO> productMap =
                products.stream().collect(Collectors.toMap(ProductVO::getId, Function.identity()));

        for (OrderItemRequest item : orderItemList) {
            int rows = productMapper.lockProductStock(item.getProductId(), item.getBuyNum());
            if (rows != 1){
                throw new BizException(BizCodeEnum.ORDER_CONFIRM_LOCK_PRODUCT_FAIL);
            }
            // 2、新增商品锁定记录
            ProductVO product = productMap.get(item.getProductId());
            ProductTaskDO task = new ProductTaskDO();
            task.setProductId(item.getProductId());
            task.setLockState(StockTaskStateEnum.LOCK);
            task.setCreateTime(new Date());
            task.setOutTradeNo(orderOutTradeNo);
            task.setBuyNum(item.getBuyNum());
            task.setProductName(product.getTitle());
            int insert = productTaskMapper.insert(task);
            log.info("商品库存锁定任务新增成功【{}】", task);
            // 3、发送解除商品库存锁定mq延迟消息
            if (insert == 1){
                ProductMessage message = new ProductMessage();
                message.setTaskId(task.getId());
                message.setOutTradeNo(task.getOutTradeNo());
                message.setTime(task.getCreateTime());
                productMessageProducer.sendMsg(message);
                log.info("MQ-商品库存释放任务发送成功【{}】", message);
            }
        }
        return JsonData.buildSuccess();
    }

    /**
     * 分页查询商品列表
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public JsonData page(int page, int size) {
        IPage<ProductDO> p = new Page<>(page, size);
        IPage<ProductDO> productDOIPage = productMapper.selectPage(p, null);
        List<ProductDO> records = productDOIPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return JsonData.buildSuccess();
        }
        List<ProductVO> vos = records.stream().map(this::toVO).collect(Collectors.toList());
        PageJsonData pageJsonData = new PageJsonData(page, size, (int) p.getTotal());
        pageJsonData.setData(vos);
        return pageJsonData;
    }

    private ProductVO toVO(ProductDO product){
        ProductVO vo = new ProductVO();
        if (product == null || product.getStock() == null || product.getLockStock() == null) {
            return null; // todo 这里是否合理？
        }
        BeanUtils.copyProperties(product, vo);
        vo.setStock(product.getStock() - product.getLockStock());
        return vo;
    }
}
